<template>
  <div>
    <el-form 
			class="elForm" 
			:inline="true" 
			:model="dataForm" 
			:rules="dataRule" 
			ref="dataForm">
      <el-form-item>
        <el-button size="medium" class="add-btn" v-if="dataListSelections.length==0" @click="addHandle()">
          新建模板
        </el-button>
        <el-button size="medium" type="danger" v-if="dataListSelections.length!=0" @click="deleteHandle()">
          批量删除
        </el-button>
      </el-form-item>
      <el-form-item prop="title">
        <el-input v-model="dataForm.title" placeholder="考核名称" size="medium" class="input" clearable="clearable" />
        <el-button class="search" size="small" @click="searchHandle()" icon="el-icon-search"></el-button>
      </el-form-item>
    </el-form>
    <el-table 
			:data="dataList" 
      ref="dataTable" 
			border 
			v-loading="dataListLoading" 
			@selection-change="selectionChangeHandle" 
			style="width: 100%;" 
			size="medium" 
			:header-cell-style="{borderColor: 'rgb(235,235,235)',background: 'rgb(247,247,247)'}" 
			:cell-style="{padding: '8px 0',borderColor: 'rgb(235,235,235)'}" 
			class="elTable" 
			:row-key="getRowKeys"
			>
      <el-table-column type="selection" :selectable="selectable" header-align="center" align="center" width="50" :reserve-selection="true" />
      <el-table-column prop="title" header-align="center" align="center" label="考核名称" min-width="470" />
      <el-table-column prop="total_score" header-align="center" align="center" label="分数" min-width="140" />
      <el-table-column prop="creator" header-align="center" align="center" label="创建人" min-width="140" />
      <el-table-column prop="create_time" header-align="center" align="center" label="创建时间" min-width="175" />
      <el-table-column header-align="center" align="center" width="80" label="操作">
        <template #default="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-more cursor" style="font-size: 28px"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push({name: ''})">预览</el-dropdown-item>
                <el-dropdown-item @click="addHandle(scope.row.id)">编辑</el-dropdown-item>
                <el-dropdown-item @click="deleteHandle(scope.row.id)"  :disabled="dataListSelections.length!=0">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination 
			@size-change="sizeChangeHandle" 
			@current-change="currentChangeHandle" 
			:current-page="pageIndex" 
			:page-sizes="[10, 20, 50]" 
			:page-size="pageSize" 
			:total="totalCount" 
			layout="total, sizes, prev, pager, next, jumper"
			></el-pagination>

  </div>
</template>

<script>
export default {
  data: function() {
    return {
      dataForm: {
        title: null
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      dataListLoading: false,
      dataListSelections: []
    }
  },
  methods: {
    init() {
      let id = this.id
      if (id) {
        console.log(id)
        // 有id 是复制
        this.$http('checkList/selectCheckListById', 'post', { id }, false, resp => {
          if (resp.code == 200) {
            console.log(resp)
            let { list } = resp
            this.form.title = list.title
            this.form.time[0] = list.start_time
            this.form.time[1] = list.end_time
            this.allTemplate.map(item => {
              if (item.id == list.examTemplateId) {
                this.form.template = item.title
                return true
              }
            })
            this.selectScorer = JSON.parse(list.scorer)
            this.weight = JSON.parse(list.weight)
            let person = JSON.parse(list.person)
            person.forEach(item => {
              this.members.push(item.id)
            })
            this.updateMember()
          }
        })
      } else {
        // 没有id 是新增
      }
    },
    // 提交给后端
    onSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.weightCount != 100) {
            this.$message({
              message: '权重总和必须为100%',
              type: 'warning',
              duration: 1200
            })
            return false
          }
          let start_time = dayjs(this.form.time[0]).format('YYYY-MM-DD HH:mm:ss')
          let end_time = dayjs(this.form.time[1]).format('YYYY-MM-DD HH:mm:ss')
          let examTemplateId
          this.allTemplate.forEach(item => {
            if (item.title == this.form.template) {
              examTemplateId = item.id
              return true
            }
          })
          let data = {
            title: this.form.title,
            start_time,
            end_time,
            // person: this.members,
            person: this.users.filter(item => item.selected == true),
            examTemplateId,
            scorer: this.selectScorer,
            weight: this.weight
          }
          // console.log(data);
          this.$http('checkList/addMark', 'post', data, false, resp => {
            if (resp.code == 200) {
              this.$message({
                message: resp.msg,
                type: 'success',
                duration: 1200
              })
              setTimeout(() => {
                this.$router.push({ name: 'Exam' })
              }, 1200)
            }
          })
        } else {
          return false
        }
      })
    },
    // 删除角色
    deleteHandle(id) {
      let ids = id ? [id] : this.dataListSelections.map(item => item.id)
      console.log(ids)

      if (ids.length == 0) {
        this.$message({
          message: '没有选中记录',
          type: 'warning',
          duartion: 1200
        })
      } else {
        this.$confirm('确定要删除选中记录？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http('markTemplate/deleteTemplate', 'post', { ids }, true, resp => {
            // console.log(resp)
            if (resp.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duartion: 1200
              })
              // 清除table选中
              this.$refs.dataTable.clearSelection()
              this.loadDataList()
            } else {
              this.$message({
                message: '未能删除记录',
                type: 'warning',
                duartion: 1200
              })
            }
          })
        })
      }
    },
    // 新增 编辑 模板
    addHandle(id) {
      if (id) {
        this.$router.push({ name: 'ExamTempUpdate', params: { id: id } })
      } else {
        this.$router.push({ name: 'ExamTempAdd'})
      }
    },
    // 查询功能
    searchHandle() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$refs['dataForm'].clearValidate()
          // 后端接收到''会报错，接收null是代表没有这个条件
          if (this.dataForm.title == '') {
            this.dataForm.title = null
          }
          if (this.pageIndex != 1) {
            this.pageIndex = 1
          }
          this.loadDataList()
        } else {
          return false
        }
      })
    },
    // 加载分页数据
    loadDataList() {
      this.dataListLoading = true
      let data = {
        title: this.dataForm.title,
        page: this.pageIndex,
        length: this.pageSize
      }
      this.$http('markTemplate/selectTemplateListBypages', 'post', data, false, resp => {
        let page = resp.page
        // console.log(page);
        this.dataList = page.list
        this.dataList.forEach(item => {
          // 处理时间中间的T 如：2021-11-14T19:11:51
          item.create_time = item.create_time.replace('T', ' ')
        })
        this.totalCount = page.totalCount
        this.dataListLoading = false
      })
    },
    // 分页一页数量改变时触发
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.loadDataList()
    },
    // 分页换页时触发
    currentChangeHandle(val) {
      this.pageIndex = val
      this.loadDataList()
    },
    selectionChangeHandle: function(val) {
      this.dataListSelections = val
      console.log(this.dataListSelections)
    },
    selectable: function(row, index) {
      // console.log(row)
      if (row.systemic || row.users > 0) {
        return false
      }
      return true
    },
    // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
    getRowKeys(row) {
      return row.id
    }
  },
  created() {
    this.loadDataList()
  }
}
</script>

<style lang="scss" scoped>
@import './examTemplate.scss';
</style>
